// 负责 添加学校，修改学校的逻辑

import { reqAddSchool, reqUpdateSchool } from "@/api/reqSchool"
import type { School } from "@/types/school"
import { ElMessage, type FormInstance, type FormRules } from "element-plus"
import { reactive, ref, type Ref } from "vue"

export const useAddAndUpdateSchool = (changeRef: Ref<symbol>) => {
  // 弹窗展示
  const dialogRef = ref(false)
  // 弹窗标题
  const titleRef = ref("")
  // 定义添加按钮的事件
  const addSchoolHandler = function () {
    titleRef.value = "添加学校"
    dialogRef.value = true
  }
  // 定义表单数据
  const schoolForm = ref<School>({
    schoolname: "",
  })
  // 表单校验
  const formRules = reactive<FormRules<School>>({
    schoolname: [
      {
        required: true,
        message: "请输入学校名称",
        trigger: "blur",
      },
      {
        pattern: /^[\u4e00-\u9fa5]+$/,
        message: "学校名称只能为汉字",
        trigger: "blur",
      },
    ],
  })

  // 表单元素
  const formEle = ref<FormInstance>()
  // 初始化
  const close = () => {
    // 表单信息初始化
    formEle.value?.resetFields()
    schoolForm.value = {
      schoolname: "",
    }
    // 弹窗消失
    dialogRef.value = false
  }

  // 添加学校
  const addSchool = () => {
    // 1. 发送添加学校的请求
    formEle.value?.validate(async (isOk) => {
      if (isOk) {
        const { status, msg } = await reqAddSchool(schoolForm.value)
        if (status === 0) {
          ElMessage.success("添加成功")
          // 重新拉取数据
          changeRef.value = Symbol()
          close()
        } else {
          ElMessage.error(msg)
        }
      }
    })
  }

  // 修改函数
  const updateSchoolHandler = (school: School) => {
    dialogRef.value = true
    titleRef.value = "修改学校"
    // 记录当前的学校信息
    schoolForm.value = {
      ...school,
    }
  }

  const updateSchool = () => {
    formEle.value?.validate(async (isok) => {
      if (isok) {
        // 发送修改数据的请求
        const { msg, status } = await reqUpdateSchool(schoolForm.value)
        if (status === 0) {
          ElMessage.success("修改成功")
          //  获取更新后的数据
          //   fn(np.value, size.value)
          changeRef.value = Symbol()
          close()
        } else {
          ElMessage.error(msg)
        }
      }
    })
  }

  const addOrEdit = () => {
    if (titleRef.value === "添加学校") {
      addSchool()
    } else {
      updateSchool()
    }
  }
  return {
    dialogRef,
    titleRef,
    schoolForm,
    formRules,
    formEle,
    addOrEdit,
    close,
    addSchool,
    addSchoolHandler,
    updateSchoolHandler,
  }
}
